package Commands;

import java.io.IOException;
import java.util.Map;

import org.json.simple.*;

import Helpers.ApplicationLogger;

public abstract class ClientCommandBase<TResult> extends CommandBase implements IClientCommandExecuter, JSONAware
{
	private Map<String, String> serviceParameters;
	public Map<String, String> getServiceParameters() {
		return serviceParameters;
	}
	public void setServiceParameters(Map<String, String> serviceParameters) {
		this.serviceParameters = serviceParameters;
	}
	
	private TResult Result; 
	public TResult getResult() { return Result; } 
	protected void setResult(TResult value) { Result = value; } 

    private boolean IsNull = true;
    public boolean getIsNull() { return IsNull; } 
	protected void setIsNull(boolean value) { IsNull = value; } 
	
	public String getContentType(){
         return "application/json; charset=utf-8";
    }

    private String ClientFunctionReference;
    public String getClientFunctionReference(){ return ClientFunctionReference; }
    public void setClientFunctionReference(String value) { ClientFunctionReference = value; }

    protected abstract void ExecuteInternal() throws IOException;
    
    public void FillFromJSON(JSONObject jObj)
    {
    	setCommandName((String)jObj.get("CommandName"));
    	setSender((String)jObj.get("Sender"));
    }
    
    public ClientCommandBase() { }
    
    public final void Execute()
    {
        try {
        	ApplicationLogger.getInstance().LOG.info(getCommandName() + " execute");
			ExecuteInternal();
		} catch (IOException e) {
			e.printStackTrace();
		}  
    }
    public final ClientCommandResult GetResult()
    {
    	ClientCommandResult result = new ClientCommandResult();
        result.setIsNull(IsNull); 
        result.setNonSerializedResult(Result); 
        result.setSerializedResult(JSONValue.toJSONString(Result));
        result.setContentType(getContentType());
        
        return result;
    }
    
	public String toJSONString()
	{
		StringBuffer sb = new StringBuffer();
		sb.append("{");
		sb.append("\"" + JSONObject.escape("CommandName") + "\"");
		sb.append(":");                 
		sb.append("\"" + JSONObject.escape(getCommandName()) + "\"");
		sb.append(",");                                  
		sb.append("\"" + JSONObject.escape("CommandDescription") + "\"");
		sb.append(":");                 
		sb.append("\"" + getCommandDescription() + "\"");
		sb.append(",");
		sb.append("\"" + JSONObject.escape("Sender") + "\"");
		sb.append(":");                 
		sb.append("\"" + getSender() + "\"");
		sb.append(",");
		sb.append("\"" + JSONObject.escape("ExecuteMethod") + "\"");
		sb.append(":");
		sb.append("\"" + getExecuteMethod() + "\"");
		sb.append("}");
		return sb.toString();
	}
}
